<template>
    <div class="container">
        <div class="handle-box">
            <el-input v-model="query.Filter" class="search-input" clearable placeholder="请输入用户名"></el-input>
            <el-button type="primary" icon="el-icon-search" @click="handleSearch">查询</el-button>
            <el-button type="primary" icon="el-icon-plus" @click="openNew">新增</el-button>
        </div>
        <el-table :data="users" border class="table" ref="multipleTable">
            <el-table-column type="index" :min-width="60" :width="60" label="序号">
                <template slot-scope="scope">{{ getIndex(scope.$index) }}</template>
            </el-table-column>
            <el-table-column prop="name" label="用户名"></el-table-column>
            <el-table-column prop="userName" label="用户账号"></el-table-column>
            <el-table-column prop="phoneNumber" label="手机号码"></el-table-column>
            <el-table-column prop="email" label="邮箱"></el-table-column>
            <el-table-column label="是否启用">
                <template #default="scope">
                    <el-tag :type="scope.row.isActive ? 'success' : 'danger'">
                        {{ getDisplayText(scope.row.isActive) }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" :min-width="500" :width="500" align="center">
                <template #default="scope">
                    <el-button text icon="el-icon-edit" @click="edit(scope.row)">
                        编辑
                    </el-button>
                    <el-button text icon="el-icon-delete" class="red" @click="confirmDeleteSelected(scope.row.id)">
                        删除
                    </el-button>
                    <el-button text icon="el-icon-refresh-left"  @click="resetPassword(scope.row)">
                        重置密码
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="pagination">
            <el-pagination background layout="total, prev, pager, next"
                :current-page="query.SkipCount / query.MaxResultCount + 1" :page-size="query.MaxResultCount"
                :total="query.pageTotal" @current-change="handlePageChange"></el-pagination>
        </div>

        <el-dialog title="确认删除" :visible.sync="deleteConfirmDialogVisible" width="30%">
            <span>确定要删除吗？</span>
            <span slot="footer" class="dialog-footer">
                <el-button @click="deleteSelectedItems">确定</el-button>
                <el-button @click="deleteConfirmDialogVisible = false">取消</el-button>
            </span>
        </el-dialog>

        <el-dialog :visible.sync="dialogVisible" :title="dialogTitle" width="30%">
            <el-form ref="form" :model="user" :rules="rules" label-width="80px">
                <el-form-item label="用户名" prop="name">
                    <el-input v-model="user.name"></el-input>
                </el-form-item>
                <el-form-item label="账号" prop="userName">
                    <el-input v-model="user.userName"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password" v-if="dialogTitle == '新增'">
                    <el-input type="password" v-model="user.password" autocomplete="off" :show-password="true"></el-input>
                </el-form-item>
                <el-form-item label="是否启用">
                    <el-switch v-model="user.isActive"></el-switch>
                </el-form-item>
                <el-form-item label="手机号码">
                    <el-input v-model="user.phoneNumber"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="user.email"></el-input>
                </el-form-item>
                <el-form-item label="角色" prop="roleNames">
                    <el-select v-model="user.roleNames" placeholder="请选择角色" filterable multiple>
                        <el-option v-for="item in rolesList" :key="item.name" :label="item.name" :value="item.name">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false" v-if="this.dialogType !== 'view'">取消</el-button>
                <el-button type="primary" @click="saveUser" v-if="this.dialogType !== 'view'">保存</el-button>
            </div>
        </el-dialog>
        <el-dialog title="重置密码" :visible.sync="dialogpasswordVisible"  width="30%">
            <el-form ref="form" :model="user" :rules="rules" label-width="120px">
                <el-form-item label="用户名" label-width="120px">
                    <el-input v-model="user.name" disabled></el-input>
                </el-form-item>
                <el-form-item label="新密码密码" label-width="120px" prop="password">
                    <el-input type="password" v-model="user.password" placeholder="请输入您的新密码" autocomplete="off" :show-password="true"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogpasswordVisible = false" v-if="this.dialogType !== 'view'">取消</el-button>
                <el-button type="primary" @click="saveUser" v-if="this.dialogType !== 'view'">确定</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import { getUserByPaged, addUser, updateUser, deleteUser } from '@/api/user';
import { getRoles } from '@/api/role'
import DateTimeUtil from '@/utils/dateTimeUtil';

export default {
    components: {
    },
    data() {
        return {
            query: {
                Filter: '',
                SkipCount: 0,
                MaxResultCount: 8,
                pageTotal: 0,
            },
            dialogType: '',
            dialogVisible: false,
            dialogpasswordVisible:false,
            dialogTitle: '新增',
            filters: {},
            users: [],
            user: {},
            selectedItemId: null,
            rolesList: [],
            deleteConfirmDialogVisible: false,
            rules: {
                name: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 1, max: 6, message: '长度在 1 到 6 个字符', trigger: 'blur' }
                ],
                userName: [
                    { required: true, message: '请输入账号', trigger: 'blur' },
                    { min: 3, max: 11, message: '长度在 3 到 11 个字符', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '密码不能为空', trigger: 'blur' },
                    {
                        pattern: /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#\$%\^&\*])/,
                        message: '密码需要包含至少一位非字母数字字符、一位小写字母和一位大写字母。',
                        trigger: 'blur'
                    }
                ],
                email: [
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    { type: 'email', message: '请输入有效的邮箱', trigger: 'blur' }
                ],
                roleNames: [
                    { type: 'array', required: true, message: '请至少选择一个角色', trigger: 'change' }
                ]
            }
        }
    },
    mounted() {
        this.loadUsers();
        this.getAllRoles();
    },
    methods: {
        handleSearch() {
            if (this.query.Filter.trim() !== '') {
                this.query.SkipCount = 0;
                this.loadUsers();
            }

        },
        handlePageChange(newPage) {
            this.query.SkipCount = (newPage - 1) * this.query.MaxResultCount; // 计算正确的 SkipCount
            this.loadUsers();
        },
        async getAllRoles() {
            const res = await getRoles();
            this.rolesList = res.data.items;
        },
        resetPassword(row){
            this.user=row;
            this.dialogType="update";
            this.dialogpasswordVisible=true;
        },
        getIndex(index) {
            return index + 1;
        },
        getDisplayText(isActive) {
            return isActive ? '是' : '否';
        },

        dateTimeUtil(datetime) {
            return DateTimeUtil.convertToBeijingTime(datetime);
        },
        deleteSelectedItems() {
            deleteUser(this.selectedItemId).then(res => {
                this.$message({
                    message: "删除成功",
                    type: 'success',
                    duration: 1000 // 显示时间为1秒（1000毫秒）
                });
                this.deleteConfirmDialogVisible = false;
                this.loadUsers();
            }).catch((error) => {
                this.$message.error(error);
            })

        },
        openNew() {
            this.user = {};
            this.user.isActive=true;
            this.dialogTitle = "新增";
            this.dialogType = "add";
            this.dialogVisible = true;
        },

        refresh() {
            this.loadUsers();
        },
        saveUser() {
            this.$refs['form'].validate((valid) => {
                if (valid) {
                    if (this.dialogType == "add") {
                        this.user.lockoutEnabled=true;
                        addUser(this.user).then(res => {
                            this.$message({
                                message: "新增成功",
                                type: 'success',
                                duration: 1000 // 显示时间为1秒（1000毫秒）
                            });
                            this.dialogVisible = false;
                            this.loadUsers();
                        }).catch((error) => {
                            this.$message.error(error);
                        });
                    }
                    else {
                        updateUser(this.user.id, this.user).then(res => {
                            this.$message({
                                message: "操作成功",
                                type: 'success',
                                duration: 1000 // 显示时间为1秒（1000毫秒）
                            });
                            this.dialogVisible = false;
                            this.dialogpasswordVisible=false;
                            this.loadUsers();
                        }).catch((error) => {
                            this.$message.error(error);
                        });
                    }
                } else {
                    alert('请完善信息!');
                    return false;
                }
            });

        },
        edit(user) {
            this.dialogTitle = '编辑';
            this.dialogVisible = true;
            this.dialogType = "update";
            this.user = user;
        },
        confirmDelete(user) {

        },
        confirmDeleteSelected(id) {
            this.deleteConfirmDialogVisible = true;
            this.selectedItemId = id;
        },
        exportCSV() {
            this.$refs.dt.exportCSV();
        },
        loadUsers() {
            getUserByPaged(this.query)
                .then((res) => {
                    this.query.pageTotal = res.totalCount;
                    this.users = res.items;
                })
                .catch((error) => {
                    this.$message.error(error);
                });
        }
    }
}
</script>
